<?php
/**
 * @version		$Id: example.php 9764 2007-12-30 07:48:11Z ircmaxell $
 * @package		Joomla
 * @subpackage	Content
 * @copyright	Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 * Joomla! is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * See COPYRIGHT.php for copyright notices and details.
 */

// Check to ensure this file is included in Joomla!
defined( '_JEXEC' ) or die();

jimport( 'joomla.plugin.plugin' );

/**
 * Example Content Plugin
 *
 * @package		Joomla
 * @subpackage	Content
 * @since 		1.5
 */
class plgContentStatZone_BattingStats extends JPlugin
{

	/**
	 * Constructor
	 *
	 * For php4 compatability we must not use the __constructor as a constructor for plugins
	 * because func_get_args ( void ) returns a copy of all passed arguments NOT references.
	 * This causes problems with cross-referencing necessary for the observer design pattern.
	 *
	 * @param object $subject The object to observe
	 * @param object $params  The object that holds the plugin parameters
	 * @since 1.5
	 */
	function plgContentStatZone_BattingStats( &$subject, $params )
	{
		parent::__construct( $subject, $params );
        
        // load plugin parameters
        $this->_plugin = JPluginHelper::getPlugin( 'Content', 'StatZone_BattingStats' );
        $this->_params = new JParameter( $this->_plugin->params );
    }
    
    
    /**
	 * PlayerClub prepare content method
	 *
	 * Method is called by the view
	 *
	 * @param 	object		The article object.  Note $article->text is also available
	 * @param 	object		The article params
	 * @param 	int			The 'page' number
	 */
	function onPrepareContent( &$article, &$params, $limitstart )
	{
        global $mainframe;
        $id = $article->id;
        
              
        // expression to search for
        $regex = '/{StatZoneBattingStats}/i';
        
        // checking
		if ( !preg_match($regex, $article->text)  ) {
			return;
		}
        
        $db =& JFactory::getDBO();
        
        //Stats are shown by getting the current season and prev seasons
        //Then they are grouped by Team and by Game type (1 or 2 dayers)
        
        
        //1. lets first start by getting the team ids of this player (can b >1) and the playerid from the contentid
        //Union all teams this player has played for, could be for different clubs (cant use statzone_teamplayers since it only stores current team)
        $sql ='SELECT DISTINCT t.id as id, t.name, p.firstname, p.surname, p.id as playerid
              FROM #__statzone_players AS p 
              INNER JOIN  #__statzone_battingscores batsc ON p.id = batsc.playerid
              INNER JOIN #__statzone_teams AS t ON t.id = batsc.teamid
              WHERE p.contentid =  '. $id   
        ;
        
        $db->setQuery( $sql );
        if (!$db->query())
		{
			echo JError::raiseWarning( 500, $db->getErrorMsg() );
            $article->text = preg_replace( $regex, '', $article->text );
            return;
		}
        
        $teamids = $db->loadObjectList();
        
        $playerid = $teamids[0]->playerid; //the player id will be the same for all rows returned- it better be
        
        //2. Get a list of all distinct seasons for this player AND its published
        $sql ='SELECT DISTINCT sc.season AS season '
        .'  FROM #__statzone_scorecards AS sc '
        .'  INNER JOIN #__statzone_battingscores AS bs ON bs.scorecardid = sc.id'
        .'  INNER JOIN #__statzone_players AS p ON p.id = bs.playerid'
        .'  WHERE p.contentid = ' . $id
        .'  AND sc.published = 1'
        ;
        $db->setQuery( $sql );
        if (!$db->query())
		{
			echo JError::raiseWarning( 500, $db->getErrorMsg() );
            $article->text = preg_replace( $regex, '', $article->text );
            return;
		}
        $seasons = $db->loadObjectList();
        
        //3. What is the current season:
        $currentSeason = '';
        $currentDateMonth = date('m');
        $currentDateYear = date('Y');
        if($currentDateMonth < 7) //before july
        {
            $currentSeason = ($currentDateYear - 1) . '/' . $currentDateYear ; //2007/2008
        }
        else
        {
            $currentSeason = $currentDateYear . '/' . ($currentDateYear + 1); //2008/2009
        }
        
        if(count($seasons) == 0)
        {
            //No seasons played...says so and return
            $article->text = preg_replace( $regex, 'No batting stats recorded yet.', $article->text );
            return;
        }
        
                        
        //_____Get the current seasons stats_____
        $currentseason_data = '';
        foreach($seasons as $seasonrow)
        {
            //if the season is = current season then dont put it in a slide
            if(trim($seasonrow->season) == trim($currentSeason))
            {
                $testBool = trim($seasonrow->season) == trim($currentSeason);
                //prep the div where all the current seasons batting stats are going into
                $currentseason_div = '<div><h3>Batting stats current season: ' . $currentSeason.'</h3>{seasonsbattingstats_current}</div>';
                
                //group the stats by teams played for:
                $currentseason_stats='';
                
                //get 1 day games first
                foreach($teamids as $teamrecord)           
                {
                    $teamname_playingfor = $teamrecord->name;
                    $teamid = $teamrecord->id;
                    $currentseason_stats = $currentseason_stats . plgContentStatZone_BattingStats::getStatsTableForPlayerInTeam($teamid , $playerid, $teamname_playingfor, true,$seasonrow->season);
                }
                //now get 2 day games
                foreach($teamids as $teamrecord)           
                {
                    $teamname_playingfor = $teamrecord->name;
                    $teamid = $teamrecord->id;
                    $currentseason_stats = $currentseason_stats . plgContentStatZone_BattingStats::getStatsTableForPlayerInTeam($teamid , $playerid, $teamname_playingfor, false,$seasonrow->season);
                }
                
                //merge the div with the data
                $currentseason_data = preg_replace( '/{seasonsbattingstats_current}/i', $currentseason_stats, $currentseason_div);
            }
        }
        
        //____Get the previous seasons stats_______
        $prevseason_data = '';
        $prevseason_stats  = '';
        foreach($seasons as $seasonrow)
        {
            if($seasonrow->season != $currentSeason)
            {
                               
                //prep the div where all the Prev seasons batting stats are going into
                $prevseason_div = ''. $seasonrow->season .'{seasonsbattingstats_prev}';
                
                /*
                '<br/>
                                   <table>
                                        <tr><td>'. $seasonrow->season .'</td></tr>
                                    </table>
                                   {seasonsbattingstats_prev}';
                */
                
                //group the stats by teams played for:
                //1 dayes first
                foreach($teamids as $teamrecord)           
                {
                    $teamname_playingfor = $teamrecord->name;
                    $teamid = $teamrecord->id;
                    $prevseason_stats = $prevseason_stats  . plgContentStatZone_BattingStats::getStatsTableForPlayerInTeam($teamid , $playerid, $teamname_playingfor, true,$seasonrow->season);
                }
                
                //then 2 dayers
                foreach($teamids as $teamrecord)           
                {
                    $teamname_playingfor = $teamrecord->name;
                    $teamid = $teamrecord->id;
                    $prevseason_stats = $prevseason_stats  . plgContentStatZone_BattingStats::getStatsTableForPlayerInTeam($teamid , $playerid, $teamname_playingfor, false,$seasonrow->season);
                }
                //merge the div with the data
                $prevseason_div = preg_replace( '/{seasonsbattingstats_prev}/i', $prevseason_stats, $prevseason_div);
            }
        }
        if($prevseason_stats > '')
        {
            $prevseason_data = '{slide=Batting stats prior seasons}'.$prevseason_div.'{/slide}';
        }
        
                
        //join all the stats html
        $html = $currentseason_data .'<br>'. $prevseason_data;
        
        //render
        $article->text = preg_replace( $regex, $html, $article->text );
    
    }
	/**
	 * Gets a fully formatted html table with the stats data given the params
	 *
	 */
	function getStatsTableForPlayerInTeam( &$teamid , &$playerid, &$teamname_playingfor, $oneDayers, &$season)
	{
        $db =& JFactory::getDBO();
        $regex = '/{StatZoneBattingStats}/i';
        
        $statstable = '';
        $gameType = $oneDayers ? "1" : "2";
        
        if($oneDayers)
        {
            $sql ='SELECT DISTINCT sc.id AS id,sc.teamidhome as teamid, playerteam.name as playerteamname, '
                                .' sc.teamidhome, sc.teamidopponent, sc.firstinndate, sc.secondinndate, sc.innings AS inningscount,opponentteam.name as opponent,'
                                .' bs1.runs,bs1.notout, bs1.inningsno '
                  .' FROM #__statzone_scorecards AS sc '
                  .' INNER JOIN #__statzone_battingscores AS bs1 ON bs1.scorecardid = sc.id AND bs1.inningsno = 1 AND bs1.playerid = ' . $playerid
                  .' INNER JOIN #__statzone_teams AS playerteam ON playerteam.id = sc.teamidhome'
                  .' INNER JOIN #__statzone_teams AS opponentteam ON opponentteam.id = sc.teamidopponent'
                  .' WHERE sc.teamidhome = ' . $teamid
                  .' AND sc.published = 1'
                  .' AND sc.innings = 1'
                  .' AND sc.season = \'' . $season . '\''
                  .' AND bs1.id is not null'
                  .' ORDER BY sc.firstinndate DESC'
                ;
                
                 //echo '<br><br>'.$sql;
        }
        else
        {
            $sql ='SELECT DISTINCT sc.id AS id,sc.teamidhome as teamid, playerteam.name as playerteamname, '
                                .' sc.teamidhome, sc.teamidopponent, sc.firstinndate, sc.secondinndate, sc.innings AS inningscount,opponentteam.name as opponent,'
                                .' bs1.runs,bs1.notout, bs1.inningsno, bs1.id as bs1id,'
                                .' bs2.runs as runs2, bs2.notout as notout2, bs2.inningsno as inningsno2, bs2.id as bs2id'
                  .' FROM #__statzone_scorecards AS sc '
                  .' LEFT JOIN #__statzone_battingscores AS bs1 ON bs1.scorecardid = sc.id AND bs1.inningsno = 1 AND bs1.playerid = ' . $playerid
                  .' LEFT JOIN #__statzone_battingscores AS bs2 ON bs2.scorecardid = sc.id AND bs2.inningsno = 2 AND bs2.playerid = ' . $playerid
                  .' INNER JOIN #__statzone_teams AS playerteam ON playerteam.id = sc.teamidhome'
                  .' INNER JOIN #__statzone_teams AS opponentteam ON opponentteam.id = sc.teamidopponent'
                  .' WHERE sc.teamidhome = ' . $teamid
                  .' AND sc.published = 1'
                  .' AND sc.innings = 2'
                  .' AND sc.season = \'' . $season . '\''
                  .' ORDER BY sc.firstinndate DESC'
                ;
                
                //echo '<br><br>'.$sql;
        }
        
        
        $db->setQuery( $sql );
        if (!$db->query())
        {
            echo '<br><br>ERROR:' . $sql . '<br><br>DBERRMSG: '. $db->getErrorMsg();//JError::raiseWarning( 500, $db->getErrorMsg() );
            $article->text = preg_replace( $regex, 'ERRRROR', $article->text );
            return;
        }
        $stats = $db->loadObjectList();
                
        if(count($stats) == 0) 
        {
            //no stats for this team
            $statstable = ''
             .'<table width="100%" border="0" cellspacing="0" cellpadding="0">'
                    .'<thead>'
                        .'<tr>'
                         .'<td width="100%"  nowrap="true">No batting stats for '.$teamname_playingfor.'</td>'
                        .'</tr>'
                    .'</thead>'
            .'</table>'
            ;
            
            return '' ;
        } 
        
        //lets prebuild the table cos we know there is stats for this player in this team
        $statstable = ''
                    .'<table width="100%" border="0" cellspacing="0" cellpadding="0">'
                    .'<thead>'
                        .'<tr><td colspan=9><h4>'.$teamname_playingfor.' ('.$gameType.' day games)</h4></td></tr>'
                        .'<tr>'
                            .'<th width="10%" nowrap="true" class="sectiontableheader">Date</th>'
                            .'<th width="50%" nowrap="true" class="sectiontableheader">Opponent</th>'
                            .'<th width="5%" nowrap="true" class="sectiontableheader">Inn</th>'
                            .'<th width="5%" nowrap="true" class="sectiontableheader">NO</th>'
                            .'<th width="5%" nowrap="true" class="sectiontableheader">Runs</th>'
                            .'<th width="5%" nowrap="true" class="sectiontableheader">HS</th>'
                            .'<th width="5%" nowrap="true" class="sectiontableheader">Ave</th>'
                            .'<th width="5%" nowrap="true" class="sectiontableheader">50</th>'
                            .'<th width="5%" nowrap="true" class="sectiontableheader">100</th>'
                            .'<th width="5%" nowrap="true" class="sectiontableheader">Ducks</th>'
                        .'</tr>'
                    .'</thead>'
                    .'<tbody>'
                    .'<tr class="sectiontableentry2">{statssummary}</tr>'
                    . '{statsrowshtml}'
                    .'</tbody>'
                    .'</table>'
         ;           
        $i = 0;
        $statsrowshtml = '';//'<tr class="sectiontableheader">Playing for '.$teamname_playingfor.'<td></tr>';
        $summary_innCount = 0;
        $summary_runs = 0;
        $summary_hs = 0;
        $summary_ave = 0;
        $summary_fifties = 0;
        $summary_centuries = 0;
        $summary_ducks = 0;
        $summary_notOuts = 0;
        $summary_gameCount = 0;
        
        foreach($stats as $statsrows)
        {
            $statsrows->inndate = $statsrows->inningsno == 1 ? $statsrows->firstinndate : $statsrows->secondinndate;
            $statsrows->inndate = date('Y-m-d',strtotime($statsrows->inndate)); //format it
            
            if($statsrows->inningscount == 2 & ($statsrows->bs1id == null & $statsrows->bs2id == null))
            {
                //no stats so skip this record
                continue;
            }
            
            $summary_gameCount+=1;
            $innCountForGame = 0;
            if($statsrows->inningsno != null)
            {
                $innCountForGame++;
            }
            if($statsrows->inningsno2 != null)
            {
                $innCountForGame++;
            }
            
            
            $totalruns = $statsrows->runs + $statsrows->runs2;
            $average = 0;
            $notoutscount = 0;
            if($statsrows->notout)
            {
                $notoutscount++;
            }
            if($statsrows->notout2)
            {
                $notoutscount++;
            }
            
            //calc average
            if($innCountForGame == 2)
            {
                if($notoutscount >= $innCountForGame) //should not be >, but play it safe
                {
                    $average = $totalruns;
                }
                else
                {
                    $average = $totalruns / ($innCountForGame -$notoutscount); //notoutscount can only be 1
                }
            }
            else if($innCountForGame == 1)
            {
                $average = $totalruns; // this is a little silly i know. Client wants the stats table for innings to have running averages...which this is for 1 day games!
            }
            else
            {
                //not aware of this game type
                $average = $totalruns + "^";
            }
            
            
            //high score
            $hs = $statsrows->runs > $statsrows->runs2 ? $statsrows->runs : $statsrows->runs2;
            
            //calc 50s - TODO: 154* is 1 century and 1 fifty!! modify logic
            $fifties = 0;
            $centuries = 0;
            
            if($statsrows->runs >= 50  & $statsrows->runs < 100)
            { 
                $fifties++ ;
            }
            else if($statsrows->runs >= 100 & $statsrows->runs < 150)
            { 
                $centuries++ ;
            }
            else if($statsrows->runs >= 150 & $statsrows->runs < 200) 
            {
                $fifties++ ;
                $centuries++ ;
            }
            else if($statsrows->runs >= 250 & $statsrows->runs < 300) 
            {
                $fifties++ ;
                $centuries++ ;
                $centuries++ ;
            }
            
            if($statsrows->runs2 >= 50  & $statsrows->runs2 < 100)
            { 
                $fifties++ ;
            }
            else if($statsrows->runs2 >= 100 & $statsrows->runs2 < 150)
            { 
                $centuries++ ;
            }
            else if($statsrows->runs2 >= 150 & $statsrows->runs2 < 200) 
            {
                $fifties++ ;
                $centuries++ ;
            }
            else if($statsrows->runs2 >= 250 & $statsrows->runs2 < 300) 
            {
                $fifties++ ;
                $centuries++ ;
                $centuries++ ;
            }
            
            //Ducks
            $ducks = 0;
            if($statsrows->runs !=null && ($statsrows->runs == 0 & $statsrows->notout == 0))
            { 
                $ducks++ ;
            }
            if($statsrows->runs2 !=null && ($statsrows->runs2 == 0 & $statsrows->inningscount == 2 & $statsrows->notout2 == 0))
            { 
                $ducks++ ;
            }
            
            $rowentryclass = ($i % 2 == 0) ? 'sectiontableentry1' : 'sectiontableentry2';
            
            $statsrowshtml = $statsrowshtml
                        .'<tr class="'.$rowentryclass.'">'
                            .'<td >'. $statsrows->inndate .'</td>'
                            //.'<td width="30"  nowrap="true">'.$statsrows->playerteamname.  '</td>'
                            .'<td nowrap="true">'.$statsrows->opponent.  '</td>'
                            .'<td >'. $innCountForGame . '</td>'//.'<td >'. $statsrows->inningscount . '</td>'
                            .'<td >'. $notoutscount . '</td>'
                            .'<td >'. $totalruns . '</td>'
                            .'<td >'. $hs .'</td>'
                            .'<td >'. number_format($average,2) .'</td>'
                            .'<td >'. $fifties .'</td>' 
                            .'<td >'. $centuries.'</td>' 
                            .'<td >'. $ducks .'</td>' 
                        .'</tr>';
            
            //add to summary
            $summary_innCount += $innCountForGame;//$statsrows->inningscount;
            $summary_runs += $totalruns;
            $summary_notOuts +=  $notoutscount;
            $summary_fifties += $fifties;
            $summary_centuries += $centuries;
            $summary_ducks += $ducks;
            //get hs
            if($statsrows->runs > $summary_hs)
            {
                $summary_hs = $statsrows->runs;
            }
            if($statsrows->runs2 > $summary_hs)
            {
                $summary_hs = $statsrows->runs2;
            }
            
            $i++;
        }

        //create the summary row
        $summary_ave = 0;
        if(($summary_innCount - $summary_notOuts) == 0)
        {
            $summary_ave = $summary_runs;
        }
        else
        {
            $summary_ave = $summary_runs / ($summary_innCount - $summary_notOuts);
        }
        
        $summaryrowhtml = ''
        .'<td colspan=2>All '.$summary_gameCount.' games</td>'
        .'<td>'.$summary_innCount.'</td>'
        .'<td>'.$summary_notOuts.'</td>'
        .'<td>'.$summary_runs.'</td>'
        .'<td>'.$summary_hs.'</td>'
        .'<td>'.number_format($summary_ave,2) .'</td>'
        .'<td>'.$summary_fifties.'</td>'
        .'<td>'.$summary_centuries.'</td>'
        .'<td>'.$summary_ducks.'</td>'
        ;
        
        //now insert the stats rows into the prebuilt table
        $statstable = preg_replace( '/{statsrowshtml}/i', $statsrowshtml, $statstable );
        $statstable = preg_replace( '/{statssummary}/i', $summaryrowhtml, $statstable );
        return $statstable;
    }
    
	/**
	 * Example after display title method
	 *
	 * Method is called by the view and the results are imploded and displayed in a placeholder
	 *
	 * @param 	object		The article object.  Note $article->text is also available
	 * @param 	object		The article params
	 * @param 	int			The 'page' number
	 * @return	string
	 */
	function onAfterDisplayTitle( &$article, &$params, $limitstart )
	{
		global $mainframe;

		return '';
	}

	/**
	 * Example before display content method
	 *
	 * Method is called by the view and the results are imploded and displayed in a placeholder
	 *
	 * @param 	object		The article object.  Note $article->text is also available
	 * @param 	object		The article params
	 * @param 	int			The 'page' number
	 * @return	string
	 */
	function onBeforeDisplayContent( &$article, &$params, $limitstart )
	{
		global $mainframe;
        
        return '';
	}

	/**
	 * Example after display content method
	 *
	 * Method is called by the view and the results are imploded and displayed in a placeholder
	 *
	 * @param 	object		The article object.  Note $article->text is also available
	 * @param 	object		The article params
	 * @param 	int			The 'page' number
	 * @return	string
	 */
	function onAfterDisplayContent( &$article, &$params, $limitstart )
	{
		global $mainframe;
        $id 	= $row->id;
	    $html 	= '';
        /*
        //find the player id
        $html = 'Batting average = 33.54'
        .       '3 x 50\'s'
        .       '1 x 100\'s'
        .       '['.$id.']'
        ;
        //get the players batting ave
        
        //get the players no of 50's and no of 100's
*/
		return $html;
	}
}
// ALTER TABLE `jos_statzone_battingscores` CHANGE `overs` `balls` INT( 11 ) NULL DEFAULT NULL  